package com.share.cloudStorage.files.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.cloudStorage.files.dao.FilesDao;
import com.share.cloudStorage.files.model.Files;
import com.share.cloudStorage.files.model.FilesQueryParams;
import com.share.cloudStorage.folders.service.FoldersService;
import com.share.cloudStorage.hdfs.HdfsClient;
import com.share.cloudStorage.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
import java.util.List;
@Slf4j
@Service
public class FilesServiceImpl extends ServiceImpl<FilesDao, Files> implements FilesService {
    @Autowired
    private FilesDao filesDao;
    @Autowired
    private HdfsClient hdfsClient;
    @Autowired
    private FoldersService foldersService;

    @Override
    public List<Files> searchFilesById(FilesQueryParams filesQueryParams) {
        log.info("----{}",filesQueryParams);
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        if (filesQueryParams.getFolderId()!=null){
            queryWrapper.eq("parent_id",filesQueryParams.getFolderId());
        }
        if (filesQueryParams.getSearchQuery()!=null && filesQueryParams.getSearchQuery()!=""){
            queryWrapper.like("file_name",filesQueryParams.getSearchQuery());
        }
        queryWrapper.eq("user_id", filesQueryParams.getUserId());
        List<Files> files = filesDao.selectList(queryWrapper);
        return files;
    }
//递归删除文件
    @Override
    public String deleteFiles(int[] ids) {
        log.info("ids:{}",ids);
        if (ids.length>0){
            List<Integer> list = new ArrayList<>();
            for (int id : ids) {
                list.add(id);
            }
            filesDao.deleteById(list,1);
        }
        return "删除成功";
    }
//递归删除单个文件
    @Override
    public String updateFilesIsDelete(Files files) {
        List<Integer> list = new ArrayList<>();
        list.add(files.getFileId());
        Boolean isDelete = files.getIsDelete();
        if (isDelete){
            filesDao.deleteById(list,1);
        }else {
            filesDao.deleteById(list,0);
        }
        return "修改成功";
    }

    @Override
    public void recycleByIds(List<Integer> intFileIds) {
        filesDao.recycleByIds(intFileIds,1);
    }

    @Override
    public List<Files> searchVisibleFilesById(FilesQueryParams filesQueryParams) {
        log.info("----{}", filesQueryParams);
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        if (filesQueryParams.getFolderId() != null) {
            queryWrapper.eq("parent_id", filesQueryParams.getFolderId());
        }
        if (filesQueryParams.getSearchQuery() != null && filesQueryParams.getSearchQuery() != "") {
            queryWrapper.like("file_name", filesQueryParams.getSearchQuery());
        }
        if (filesQueryParams.getFileType() !=null && filesQueryParams.getFileType() !=""){
            queryWrapper.like("file_type",filesQueryParams.getFileType());
        }
        queryWrapper.eq("is_delete", 0);
        queryWrapper.eq("is_recycle", 0);
        queryWrapper.eq("user_id", filesQueryParams.getUserId());
        List<Files> files = filesDao.selectList(queryWrapper);
        return files;
    }

    //通过id查询分享的文件
    @Override
    public List<Files> searchByFileId(Integer fileId) {
        return filesDao.searchByFileId(fileId);
    }

    //还原文件
    @Override
    public void restoreFiles(List<Integer> intFileIds) {
        filesDao.recycleByIds(intFileIds,0);
    }

    //查询文件以及他的父id
    @Override
    public List<Integer> searchFileIdAndParentId(List<Integer> fileIdList) {
        return filesDao.searchFileIdAndParentId(fileIdList);
    }

    //上传文件
    @Transactional
    public Result uploadFile(MultipartFile file, Files files)  {
        String folderName = foldersService.getFolderNameById(files.getUserId());
        String fileName = files.getFileName();
        String[] strings = fileName.split("\\.");
        files.setFileType(strings[1].toUpperCase()+"文件");
        try{
            filesDao.insert(files);
            InputStream inputStream = file.getInputStream();
            hdfsClient.uploadFile(inputStream,folderName,files);
        }catch (Exception e){
            // 手动回滚数据库操作
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("文件上传失败:{}",e.getMessage(),e);
            return Result.fail("文件上传失败");
        }
        return Result.ok("文件上传成功");
    }

    //重命名文件
    @Transactional
    public Result reName(Files files){
        String folderName = foldersService.getFolderNameById(files.getUserId());
        try {
            hdfsClient.reName(files,folderName);
            files.setFileName(files.getNewFileName());
            files.setFilePath(files.getNewFilePath());;
            filesDao.updateById(files);
        } catch (IOException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("重命名失败:{}",e.getMessage(),e);
        }
        return Result.ok("重命名成功");
    }

    //新建文件夹
    @Transactional
    public Result createFolder(Files files){
        String folderName = foldersService.getFolderNameById(files.getUserId());
            String baseFilePath="/"+folderName+"/"+files.getFilePath();
            String filePath=baseFilePath;
            String baseFileName=files.getFileName();
            String fileName=baseFileName;
            int count=1;
            while (hdfsClient.folderExists(filePath)){
                filePath=(baseFilePath + "(" + count +")");
                String dbFilePath=filePath.substring(13);
                fileName=baseFileName+ "(" + count +")";
                files.setFileName(fileName);
                files.setFilePath(dbFilePath);
                count ++;
            }
        try {
            filesDao.insert(files);
            hdfsClient.createFolder(filePath);
        } catch (IOException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("新建文件夹失败:{}",e.getMessage(),e);
        }
        return Result.ok("新建成功");
    }
}

